package server;

import java.sql.SQLException;
import java.util.Arrays;

import capsules.CapsuleSpecification;
import capsules.CapsuleState;
import database.DatabaseOperationsCapsules;

public class Verifier {



	private DatabaseOperationsCapsules dbOpCapsules;
	private Boolean accessSynchronized;

	

	public Verifier(DatabaseOperationsCapsules dbOpCapsules){
		this.dbOpCapsules = dbOpCapsules;
		this.accessSynchronized = new Boolean(true);
	}



	public CapsuleState getCapsuleState(CapsuleSpecification capsuleSpec)
            throws SQLException{
		synchronized (accessSynchronized) {
			CapsuleSpecification capsuleSpecification = dbOpCapsules.getCapsuleSpecification(capsuleSpec.getName());

			if(capsuleSpecification!=null){
				if(capsuleSpec.getLength() == capsuleSpecification.getLength()){
					if(capsuleSpec.getOffset() == capsuleSpecification.getLength()){
						if(Arrays.equals(capsuleSpec.getHash(),capsuleSpecification.getHash())){
							return CapsuleState.CORRECT;
						}
					}
					else if(capsuleSpec.getOffset() < capsuleSpecification.getLength() && capsuleSpec.getOffset() >= 0){
						return CapsuleState.INCOMPLETE;
					}
				}
			}

			return CapsuleState.INCORRECT;
		}
	}


	public boolean isCapsuleTemporaryComplete(String nameCapsule, String nameCapsuleTemporary,
			long offsetCapsuleTemporary) 
	throws SQLException{
		synchronized (accessSynchronized) {
			long lengthCapsule = dbOpCapsules.getLengthCapsule(nameCapsule);

			if(offsetCapsuleTemporary < lengthCapsule )
				return true;
			else
				return false;
		}
	}


	public void close()
            throws SQLException{
		synchronized (accessSynchronized) {
			if(dbOpCapsules!=null){
				dbOpCapsules.close();
			}
		}
	}


}

